<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>改图工具</title>
    <!-- 预加载关键资源 -->
    <link rel="preload" href="../../../static/element-plus/css/index.css" as="style">
    <link rel="preload" href="../../../static/vue/vue.global.js" as="script">
    <link rel="preload" href="../../../static/element-plus/js/index.full.js" as="script">
    
    <!-- 引入Element Plus样式 -->
    <link rel="stylesheet" href="../../../static/element-plus/css/index.css">
    
    <!-- 内联关键样式，避免FOUC -->
    <style>
        /* 关键样式预加载 */
        body { visibility: hidden; }
        .el-button { visibility: hidden; }
        .el-card { visibility: hidden; }
    </style>
    
    <!-- 加载遮罩层样式 -->
    <style>
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.7);
            backdrop-filter: blur(2px);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 9999;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
        }

        .loading-overlay.active {
            opacity: 1;
            visibility: visible;
        }

        .loading-spinner {
            width: 60px;
            height: 60px;
            border: 4px solid rgba(255, 255, 255, 0.3);
            border-top: 4px solid #409eff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 20px;
        }

        .loading-text {
            color: white;
            font-size: 18px;
            font-weight: 500;
            text-align: center;
            margin-bottom: 10px;
        }

        .loading-subtext {
            color: rgba(255, 255, 255, 0.8);
            font-size: 14px;
            text-align: center;
        }

        .loading-progress {
            width: 300px;
            height: 4px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 2px;
            margin-top: 15px;
            overflow: hidden;
        }

        .loading-progress-bar {
            height: 100%;
            background: linear-gradient(90deg, #409eff, #79bbff);
            border-radius: 2px;
            animation: progress 2s ease-in-out infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        @keyframes progress {
            0% { width: 0%; }
            50% { width: 70%; }
            100% { width: 100%; }
        }

        /* 按钮加载状态的额外样式 */
        .el-button.loading {
            position: relative;
            overflow: hidden;
        }

        .el-button.loading::after {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.4), transparent);
            animation: shimmer 1.5s infinite;
        }

        @keyframes shimmer {
            0% { left: -100%; }
            100% { left: 100%; }
        }
    </style>
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', sans-serif;
            background: #F6F7FA;
            height: 100vh;
            overflow: hidden;
        }

        #app {
            height: 100vh;
        }

        .container {
            width: 100%;
            height: 100vh;
            display: flex;
            padding: 10px;
            gap: 15px;
        }

        .tool-panel {
            width: 300px;
            display: flex;
            flex-direction: column;
            gap: 7px;
            padding-right: 5px;
        }

        .tool-panel .el-card {
            margin: 0;
            flex-shrink: 0;
        }
        .el-card__header{
            padding: 3px 18px;
            border-bottom: none;
        }

        .el-card__body{
            padding: 7px 15px 20px 15px;
        }

        .tool-panel .el-card:last-child {
            margin-bottom: 0;
        }


        .main-canvas {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 15px;
        }


        /*.canvas-header {*/
        /*    margin-bottom: 10px;*/
        /*}*/

        .canvas-area {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .upload-section {
            margin-bottom: 15px;
        }

        .upload-area {
            display: none;
            gap: 15px;
        }

        .upload-area.active {
            display: flex;
        }

        .upload-area:not(.blend-upload) {
            flex-direction: column;
            align-items: center;
        }

        .blend-upload {
            flex-direction: row;
            justify-content: space-between;
            align-items: center;
            gap: 20px;
            flex-wrap: nowrap;
            width: 100%;
        }

        .blend-upload .upload-box {
            flex: 1;
            max-width: calc(50% - 10px);
            height: 150px;
            min-width: 0;
        }

        .upload-box {
            width: 180px;
            height: 150px;
            border: 2px dashed #dcdfe6;
            border-radius: 8px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            transition: all 0.3s;
        }

        .upload-box:hover {
            border-color: #409eff;
            background: #f0f9ff;
        }

        .upload-box img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }

        .canvas-container {
            flex: 1;
            position: relative;
            border: 1px solid #e4e7ed;
            border-radius: 8px;
            overflow: hidden;
            background: white;
        }

        canvas {
            position: absolute;
            top: 0;
            left: 0;
            cursor: crosshair;
            image-rendering: -webkit-optimize-contrast;
            image-rendering: crisp-edges;
            image-rendering: pixelated;
        }

        #backgroundCanvas {
            z-index: 1;
        }

        #drawingCanvas {
            z-index: 2;
        }

        .canvas-controls {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .color-picker {
            position: fixed;
            top: 5px;
            right: 20px;
            background: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
            z-index: 1000;
            pointer-events: auto;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .tool-group {
            display: flex;
            gap: 6px;
            margin-bottom: 15px;
            flex-wrap: wrap;
            align-items: center;
        }

        .tool-group .el-button:not(.el-button-group .el-button) {
            margin-left: 0;
        }

        .slider-label {
            display: block;
            margin-bottom: 3px;
            font-size: 10px;
            color: #606266;
        }

        @media (max-width: 768px) {
            .container {
                flex-direction: column;
                padding: 10px;
            }

            .tool-panel {
                width: 100%;
                order: 2;
            }

            .main-canvas {
                order: 1;
            }

            .blend-upload {
                flex-direction: column;
                align-items: center;
                gap: 15px;
                width: 100%;
            }
            
            .blend-upload .upload-box {
                width: 100%;
                max-width: 100%;
                height: 200px;
            }

            .canvas-controls {
                flex-direction: column;
            }

            .canvas-controls .el-button {
                width: 100%;
            }
        }
    </style>
</head>
<body>
<!-- 全局加载遮罩层 -->
<div class="loading-overlay" id="loadingOverlay">
    <div class="loading-spinner"></div>
    <div class="loading-text">图片处理中...</div>
    <div class="loading-subtext">请稍候，正在为您生成高质量图片</div>
    <div class="loading-progress">
        <div class="loading-progress-bar"></div>
    </div>
</div>

<div id="app">
    <div class="container">
        <!-- 左侧工具栏 -->
        <div class="tool-panel">
                        <!-- 图片上传区域 -->
            <div class="upload-section">
                <!-- 单图模式上传框 -->
                <div class="upload-area" :class="{ active: currentMode === 'single' }">
                    <div class="upload-box" @click="uploadSingleImage">
                        <div>上传图片</div>
                        <img id="singleImage" style="display: none;">
                    </div>
                </div>
                
                <!-- 融合模式上传框 -->
                <div class="upload-area blend-upload" :class="{ active: currentMode === 'blend' }">
                    <div class="upload-box" @click="uploadImage('base')">
                        <div>基础图片</div>
                        <img id="baseImage" style="display: none;">
                    </div>
                    <div class="upload-box" @click="uploadImage('blend')">
                        <div>融合图片</div>
                        <img id="blendImage" style="display: none;">
                    </div>
                </div>
            </div>
            <!-- 绘图工具 -->
            <el-card>
                <template #header>
                    <div class="card-header">绘图工具</div>
                </template>
                <div class="tool-group">
                    <el-button-group>
                    <el-button :type="currentTool === 'brush' ? 'primary' : 'default'" @click="setTool('brush')" size="small">
                        画笔
                    </el-button>
                        <el-button :type="currentTool === 'rectangle' ? 'primary' : 'default'" @click="setTool('rectangle')" size="small">
                        矩形
                    </el-button>
                    <el-button :type="currentTool === 'lasso' ? 'primary' : 'default'" @click="setTool('lasso')" size="small">
                        套索
                    </el-button>
                    <el-button :type="currentTool === 'eraser' ? 'primary' : 'default'" @click="setTool('eraser')" size="small" :disabled="currentTool === 'rectangle' || currentTool === 'lasso'">
                        橡皮
                    </el-button>
                    </el-button-group>
                    
                    <el-button-group>
                        <el-button @click="clearCanvas" size="small" type="danger">
                            清除
                        </el-button>
                        <el-button @click="undo" size="small" :disabled="historyStack.length <= 1">
                            撤销
                        </el-button>
                    </el-button-group>
                </div>
                <div>
                    <span class="slider-label">{{ currentTool === 'eraser' ? '橡皮擦大小' : '画笔大小' }}</span>
                    <el-slider v-model="brushSize" :min="1" :max="20" :marks="{1: '1', 5: '5', 10: '10', 15: '15', 20: '20'}"></el-slider>
                </div>
            </el-card>

            <!-- 正向提示词 -->
            <el-card>
                <template #header>
                    <div class="card-header">正向提示词</div>
                </template>
                <el-button-group>
                    <el-button @click="copyToClipboard('positive')" size="small">
                        复制
                    </el-button>
                    <el-button @click="translateText('positive')" size="small">
                        翻译
                    </el-button>
                    <el-button @click="clearText('positive')" size="small">
                        清除
                    </el-button>
                    <el-button @click="showPromptDialog('positive')" size="small">
                        提示词
                    </el-button>
                </el-button-group>
                <el-input
                        v-model="positivePrompt"
                        type="textarea"
                        :rows="3"
                        placeholder="请输入正向提示词Prompt"
                ></el-input>
<!--                <div>-->
<!--                    <span class="slider-label">提示词引导系数 CFG scale</span>-->
<!--                    <el-slider v-model="positiveWeight" :min="1" :max="6" :marks="{1: '1', 3: '3', 6: '6'}"></el-slider>-->
<!--                </div>-->
                <div style="margin-top: 15px;">
                    <el-checkbox v-model="useAspectRatio" style="margin-bottom: 10px;">启用长宽比设置</el-checkbox>
                    <div v-if="useAspectRatio">
                        <span class="slider-label">长宽比设置</span>
                        <div style="display: flex; gap: 10px; align-items: center;">
                            <el-input-number 
                                v-model="aspectWidth" 
                                :min="1" 
                                :max="21" 
                                :controls="false"
                                placeholder="宽度" 
                                style="flex: 1;">
                            </el-input-number>
                            <span>:</span>
                            <el-input-number 
                                v-model="aspectHeight" 
                                :min="1" 
                                :max="21" 
                                :controls="false"
                                placeholder="高度" 
                                style="flex: 1;">
                            </el-input-number>
                        </div>
                    </div>
                </div>
            </el-card>
        </div>

        <!-- 主内容区域 -->
        <div class="main-canvas">
            <div class="canvas-header">
                <h3 class="module-title">画板</h3>
            </div>
            <div class="canvas-area">
                <div class="canvas-container">
                    <canvas id="backgroundCanvas" style="display: none;"></canvas>
                    <canvas id="drawingCanvas"></canvas>
                </div>

                <div class="canvas-controls">
                    <el-dropdown @command="setMode">
                        <el-button>
                            改图模式
                        </el-button>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item command="single">单图模式</el-dropdown-item>
                                <el-dropdown-item command="blend">融合模式</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                    <el-button @click="saveChanges">
                        修改图片
                    </el-button>
                    <el-button @click="downloadImage" style="margin-left: 0px">
                        下载图片
                    </el-button>
                </div>
            </div>
        </div>
    </div>

    <!-- 颜色选择器 -->
    <div class="color-picker">
        <el-color-picker v-model="brushColor" show-alpha></el-color-picker>
    </div>

    <!-- 提示词选择对话框 -->
    <el-dialog v-model="promptDialogVisible" title="选择提示词" width="30%">
        <el-select v-model="selectedPrompt" placeholder="请选择">
            <el-option label="高质量" value="高质量"></el-option>
            <el-option label="超写实" value="超写实"></el-option>
            <el-option label="卡通风格" value="卡通风格"></el-option>
            <el-option label="赛博朋克" value="赛博朋克"></el-option>
        </el-select>
        <template #footer>
                <span class="dialog-footer">
                    <el-button @click="promptDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmPrompt">确定</el-button>
                </span>
        </template>
    </el-dialog>
</div>

<input type="file" ref="fileInput" accept="image/*" style="display: none;">

<!-- 引入Vue和Element Plus -->
<script src="../../../static/vue/vue.global.js"></script>
<script src="../../../static/element-plus/js/index.full.js"></script>
<script src="../../../static/element-plus-icons/index.js"></script>

<script>
    const { createApp, ref, onMounted, watch } = Vue;

    createApp({
        setup() {
            // 响应式数据
            const isProcessing = ref(false);
            const currentTool = ref('brush');
            const isDrawing = ref(false);
            const lastX = ref(0);
            const lastY = ref(0);
            const brushSize = ref(5);
            const brushColor = ref('#000000');
            const historyStack = ref([]);
            const currentMode = ref('single');
            const positivePrompt = ref('');
            const negativePrompt = ref('');
            const positiveWeight = ref(5);
            const negativeWeight = ref(5);
            const promptDialogVisible = ref(false);
            const selectedPrompt = ref('');
            const currentPromptType = ref('');
            const aspectWidth = ref(1);
            const aspectHeight = ref(1);
            const useAspectRatio = ref(false);

            // 矩形功能相关数据
            const rectangles = ref([]);
            const selectedRectIndex = ref(-1);
            
            // 套索功能相关数据
            const lassos = ref([]);
            const selectedLassoIndex = ref(-1);
            let currentLassoPath = [];
            let isDrawingLasso = false;

            let canvas = null;
            let ctx = null;
            let originalImage = null;

            // 矩形交互状态变量
            let startX = 0, startY = 0, endX = 0, endY = 0;
            let isDraggingRect = false;
            let isResizing = false;
            let activeControlPoint = -1;
            let rectDragStartX = 0, rectDragStartY = 0;
            let dragOffsetX = 0, dragOffsetY = 0;

            // 初始化画布
            const initCanvas = () => {
                canvas = document.getElementById('drawingCanvas');
                ctx = canvas.getContext('2d', { willReadFrequently: true });
                const bgCanvas = document.getElementById('backgroundCanvas');

                const container = document.querySelector('.canvas-container');
                const newWidth = container.offsetWidth;
                const newHeight = container.offsetHeight;
                
                // 如果画布尺寸发生变化且已有图片，保持图片状态
                if (canvas.width !== newWidth || canvas.height !== newHeight) {
                    const hasImage = originalImage !== null;
                    const oldWidth = canvas.width;
                    const oldHeight = canvas.height;
                    
                    // 计算缩放比例
                    const scaleX = newWidth / oldWidth;
                    const scaleY = newHeight / oldHeight;
                    
                    // 缩放矩形数据
                    if (oldWidth > 0 && oldHeight > 0) {
                        rectangles.value.forEach(rect => {
                            rect.startX *= scaleX;
                            rect.startY *= scaleY;
                            rect.endX *= scaleX;
                            rect.endY *= scaleY;
                        });
                        
                        // 缩放套索数据
                        lassos.value.forEach(lasso => {
                            lasso.points.forEach(point => {
                                point.x *= scaleX;
                                point.y *= scaleY;
                            });
                        });
                    }
                    
                    canvas.width = newWidth;
                    canvas.height = newHeight;
                    
                    // 同步更新backgroundCanvas大小
                    if (bgCanvas) {
                        bgCanvas.width = newWidth;
                        bgCanvas.height = newHeight;
                        
                        // 如果有原始图片，重新绘制到backgroundCanvas并居中
                        if (hasImage && originalImage) {
                            const bgCtx = bgCanvas.getContext('2d');
                            bgCtx.clearRect(0, 0, bgCanvas.width, bgCanvas.height);
                            
                            const maxWidth = newWidth * 0.9;
                            const maxHeight = newHeight * 0.9;
                            const scale = Math.min(maxWidth / originalImage.width, maxHeight / originalImage.height);
                            
                            const scaledWidth = originalImage.width * scale;
                            const scaledHeight = originalImage.height * scale;
                            const offsetX = (newWidth - scaledWidth) / 2;
                            const offsetY = (newHeight - scaledHeight) / 2;
                            
                            bgCtx.drawImage(originalImage, offsetX, offsetY, scaledWidth, scaledHeight);
                        }
                    }
                    
                    redrawCanvas();
                } else if (!originalImage) {
                    // 首次初始化 - 使用透明背景
                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                    ctx.fillStyle = 'rgba(0, 0, 0, 0)';
                    ctx.fillRect(0, 0, canvas.width, canvas.height);
                    saveToHistory();
                }
            };

            // 保存历史记录
            const saveToHistory = () => {
                if (historyStack.value.length >= 20) {
                    historyStack.value.shift();
                }
                historyStack.value.push({
                    imageData: ctx.getImageData(0, 0, canvas.width, canvas.height),
                    rectangles: JSON.parse(JSON.stringify(rectangles.value)),
                    lassos: JSON.parse(JSON.stringify(lassos.value))
                });
            };

            // 撤销功能
            const undo = () => {
                if (historyStack.value.length > 1) {
                    historyStack.value.pop();
                    const previousState = historyStack.value[historyStack.value.length - 1];
                    ctx.putImageData(previousState.imageData, 0, 0);
                    rectangles.value = JSON.parse(JSON.stringify(previousState.rectangles));
                    lassos.value = JSON.parse(JSON.stringify(previousState.lassos));
                    selectedRectIndex.value = -1;
                    selectedLassoIndex.value = -1;
                    isDrawing.value = false;
                    isDraggingRect = false;
                    isResizing = false;
                    activeControlPoint = -1;
                } else {
                    ElementPlus.ElMessage.warning('没有可撤回的操作');
                }
            };

            // 设置工具
            const setTool = (tool) => {
                currentTool.value = tool;
                selectedRectIndex.value = -1;
                selectedLassoIndex.value = -1;
                isDraggingRect = false;
                isResizing = false;
                activeControlPoint = -1;
                isDrawingLasso = false;
                currentLassoPath = [];
                // --------------------------------------------------------------
                
                // 重置canvas的绘制模式
                if (ctx) {
                    ctx.globalCompositeOperation = 'source-over';
                }
                //---------------------------------------------------------------
            };

            // 清除画布
            const clearCanvas = () => {
                // 只清除绘图内容（矩形、套索、画笔痕迹），保留背景图片
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                
                // 清空所有绘图数据（矩形、套索、画笔痕迹），但保留背景图片
                rectangles.value = [];
                lassos.value = [];
                
                // 重新绘制背景图片
                redrawCanvas();
                saveToHistory();
            };

            // 设置模式
            const setMode = (mode) => {
                currentMode.value = mode;
            };

            // 获取鼠标在画布上的实际坐标
            const getCanvasCoordinates = (e) => {
                const rect = canvas.getBoundingClientRect();
                return {
                    x: (e.clientX - rect.left) * (canvas.width / rect.width),
                    y: (e.clientY - rect.top) * (canvas.height / rect.height)
                };
            };

            // 绘制所有矩形
            const drawRectangles = () => {
                rectangles.value.forEach((rect, index) => {
                    drawSingleRectangle(rect, index === selectedRectIndex.value);
                });
            };

            // 绘制所有套索
            const drawLassos = () => {
                lassos.value.forEach((lasso, index) => {
                    drawSingleLasso(lasso, index === selectedLassoIndex.value);
                });
            };

            // 绘制单个套索
            const drawSingleLasso = (lasso, isSelected) => {
                if (lasso.points.length < 2) return;

                ctx.strokeStyle = lasso.color;
                ctx.fillStyle = lasso.color + '66'; // 添加透明度（约40%不透明）
                ctx.lineWidth = 2;

                ctx.beginPath();
                ctx.moveTo(lasso.points[0].x, lasso.points[0].y);
                
                for (let i = 1; i < lasso.points.length; i++) {
                    ctx.lineTo(lasso.points[i].x, lasso.points[i].y);
                }
                ctx.closePath();
                
                ctx.fill();
                ctx.stroke();


            };

            // 绘制单个矩形
            const drawSingleRectangle = (rect, isSelected) => {
                ctx.strokeStyle = rect.color;
                ctx.fillStyle = rect.color + '66'; // 添加透明度（约40%不透明）
                ctx.lineWidth = 2;

                const width = rect.endX - rect.startX;
                const height = rect.endY - rect.startY;

                ctx.fillRect(rect.startX, rect.startY, width, height);
                ctx.strokeRect(rect.startX, rect.startY, width, height);

                if (isSelected) {
                    const controlPoints = getControlPoints(rect);
                    ctx.fillStyle = '#fff';
                    ctx.strokeStyle = '#000';
                    ctx.lineWidth = 1;

                    controlPoints.forEach(point => {
                        ctx.beginPath();
                        ctx.arc(point.x, point.y, 4, 0, Math.PI * 2);
                        ctx.fill();
                        ctx.stroke();
                    });
                }
            };

            // 获取矩形的控制点
            const getControlPoints = (rect) => {
                return [
                    { x: rect.startX, y: rect.startY }, // 左上
                    { x: rect.endX, y: rect.startY },   // 右上
                    { x: rect.endX, y: rect.endY },     // 右下
                    { x: rect.startX, y: rect.endY }    // 左下
                ];
            };

            // 判断点是否在矩形内
            const isPointInRect = (x, y, rect) => {
                return x >= rect.startX && x <= rect.endX && y >= rect.startY && y <= rect.endY;
            };

            // 判断点是否在套索内（射线法）
            const isPointInLasso = (x, y, lasso) => {
                if (lasso.points.length < 3) return false;
                
                let inside = false;
                const points = lasso.points;
                for (let i = 0, j = points.length - 1; i < points.length; j = i++) {
                    const xi = points[i].x, yi = points[i].y;
                    const xj = points[j].x, yj = points[j].y;
                    
                    if (((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi)) {
                        inside = !inside;
                    }
                }
                return inside;
            };

            // 判断点是否在控制点上
            const isOnControlPoint = (x, y, rect) => {
                const controlPoints = getControlPoints(rect);
                const threshold = 8;

                for (let i = 0; i < controlPoints.length; i++) {
                    const point = controlPoints[i];
                    const distance = Math.sqrt((x - point.x) ** 2 + (y - point.y) ** 2);
                    if (distance <= threshold) {
                        return i;
                    }
                }
                return -1;
            };

            // 重绘画布
            const redrawCanvas = () => {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                const bgCanvas = document.getElementById('backgroundCanvas');
                if (originalImage) {
                    const container = document.querySelector('.canvas-container');
                    const maxWidth = container.clientWidth * 0.9;
                    const maxHeight = container.clientHeight * 0.9;
                    const scale = Math.min(maxWidth / originalImage.width, maxHeight / originalImage.height);
                    
                    const scaledWidth = originalImage.width * scale;
                    const scaledHeight = originalImage.height * scale;
                    const offsetX = (canvas.width - scaledWidth) / 2;
                    const offsetY = (canvas.height - scaledHeight) / 2;

                    if (bgCanvas) {
                        const bgCtx = bgCanvas.getContext('2d');
                        bgCtx.clearRect(0, 0, bgCanvas.width, bgCanvas.height);
                        bgCtx.drawImage(originalImage, offsetX, offsetY, scaledWidth, scaledHeight);
                    }
                } else {
                    // 保持透明背景
                    ctx.fillStyle = 'rgba(0, 0, 0, 0)';
                    ctx.fillRect(0, 0, canvas.width, canvas.height);
                    if (bgCanvas) {
                        const bgCtx = bgCanvas.getContext('2d');
                        bgCtx.clearRect(0, 0, bgCanvas.width, bgCanvas.height);
                        bgCtx.fillStyle = 'rgba(0, 0, 0, 0)';
                        bgCtx.fillRect(0, 0, bgCanvas.width, bgCanvas.height);
                    }
                }
                drawRectangles();
                drawLassos();
            };

            // 双击删除矩形
            const handleDoubleClick = (e) => {
                if (currentTool.value === 'rectangle' && selectedRectIndex.value !== -1) {
                    rectangles.value.splice(selectedRectIndex.value, 1);
                    selectedRectIndex.value = -1;
                    redrawCanvas();
                    saveToHistory();
                } else if (currentTool.value === 'lasso' && selectedLassoIndex.value !== -1) {
                    lassos.value.splice(selectedLassoIndex.value, 1);
                    selectedLassoIndex.value = -1;
                    redrawCanvas();
                    saveToHistory();
                }
            };

            // 全局点击事件
            const handleGlobalClick = (e) => {
                if (currentTool.value === 'rectangle' && !e.target.closest('canvas')) {
                    selectedRectIndex.value = -1;
                    redrawCanvas();
                }
            };

            // 添加计算最接近的整数比例的函数
            const calculateAspectRatio = (width, height) => {
                // 计算原始比例
                const ratio = width / height;
                
                // 寻找最接近的整数比例，限制在1-21之间
                let bestWidth = 1;
                let bestHeight = 1;
                let minDiff = Math.abs(ratio - 1);
                
                for (let w = 1; w <= 21; w++) {
                    for (let h = 1; h <= 21; h++) {
                        const currentRatio = w / h;
                        const diff = Math.abs(ratio - currentRatio);
                        if (diff < minDiff) {
                            minDiff = diff;
                            bestWidth = w;
                            bestHeight = h;
                        }
                    }
                }
                
                return { width: bestWidth, height: bestHeight };
            };

            // 上传图片
            const uploadImage = (type) => {
                const fileInput = document.createElement('input');
                fileInput.type = 'file';
                fileInput.accept = 'image/*';
                fileInput.onchange = (e) => {
                    const file = e.target.files[0];
                    if (file) {
                        const reader = new FileReader();
                        reader.onload = (e) => {
                            const img = new Image();
                            img.onload = () => {
                            originalImage = img;
                            const container = document.querySelector('.canvas-container');
                            const maxWidth = container.clientWidth * 0.9;
                            const maxHeight = container.clientHeight * 0.9;
                            const scale = Math.min(maxWidth / img.width, maxHeight / img.height);

                            const scaledWidth = img.width * scale;
                            const scaledHeight = img.height * scale;

                            canvas.width = container.clientWidth;
                            canvas.height = container.clientHeight;

                            const offsetX = (canvas.width - scaledWidth) / 2;
                            const offsetY = (canvas.height - scaledHeight) / 2;

                            const bgCanvas = document.getElementById('backgroundCanvas');
                            if (bgCanvas) {
                                bgCanvas.width = canvas.width;
                                bgCanvas.height = canvas.height;
                                bgCanvas.style.display = 'block';
                                const bgCtx = bgCanvas.getContext('2d');
                                bgCtx.clearRect(0, 0, bgCanvas.width, bgCanvas.height);
                                bgCtx.drawImage(img, offsetX, offsetY, scaledWidth, scaledHeight);
                            }

                                if (type === 'base') {
                                    const baseImg = document.getElementById('baseImage');
                                    if (baseImg) {
                                        baseImg.src = e.target.result;
                                        baseImg.style.display = 'block';
                                    }
                                } else {
                                    const blendImg = document.getElementById('blendImage');
                                    if (blendImg) {
                                        blendImg.src = e.target.result;
                                        blendImg.style.display = 'block';
                                    }
                                }

                                // 计算并设置长宽比
                                const aspectRatio = calculateAspectRatio(img.width, img.height);
                                aspectWidth.value = aspectRatio.width;
                                aspectHeight.value = aspectRatio.height;
                                useAspectRatio.value = true; // 自动启用长宽比设置

                                // 清空矩形和套索选区
                                rectangles.value = [];
                                lassos.value = [];
                                selectedRectIndex.value = -1;
                                selectedLassoIndex.value = -1;

                                redrawCanvas();
                                saveToHistory();
                            };
                            img.src = e.target.result;
                        };
                        reader.readAsDataURL(file);
                    }
                };
                fileInput.click();
            };

            const uploadSingleImage = () => {
                const fileInput = document.createElement('input');
                fileInput.type = 'file';
                fileInput.accept = 'image/*';
                fileInput.onchange = (e) => {
                    const file = e.target.files[0];
                    if (file) {
                        const reader = new FileReader();
                        reader.onload = (e) => {
                            const img = new Image();
                            img.onload = () => {
                                originalImage = img;
                                const container = document.querySelector('.canvas-container');
                                const maxWidth = container.clientWidth * 0.9;
                                const maxHeight = container.clientHeight * 0.9;
                                const scale = Math.min(maxWidth / img.width, maxHeight / img.height);

                                const scaledWidth = img.width * scale;
                                const scaledHeight = img.height * scale;

                                canvas.width = container.clientWidth;
                                canvas.height = container.clientHeight;

                                const offsetX = (canvas.width - scaledWidth) / 2;
                                const offsetY = (canvas.height - scaledHeight) / 2;

                                const bgCanvas = document.getElementById('backgroundCanvas');
                                if (bgCanvas) {
                                    bgCanvas.width = canvas.width;
                                    bgCanvas.height = canvas.height;
                                    bgCanvas.style.display = 'block';
                                    const bgCtx = bgCanvas.getContext('2d');
                                    bgCtx.clearRect(0, 0, bgCanvas.width, bgCanvas.height);
                                    bgCtx.drawImage(img, offsetX, offsetY, scaledWidth, scaledHeight);
                                }

                                const singleImg = document.getElementById('singleImage');
                                if (singleImg) {
                                    singleImg.src = e.target.result;
                                    singleImg.style.display = 'block';
                                }

                                // 计算并设置长宽比
                                const aspectRatio = calculateAspectRatio(img.width, img.height);
                                aspectWidth.value = aspectRatio.width;
                                aspectHeight.value = aspectRatio.height;
                                useAspectRatio.value = true; // 自动启用长宽比设置

                                // 清空矩形和套索选区
                                rectangles.value = [];
                                lassos.value = [];
                                selectedRectIndex.value = -1;
                                selectedLassoIndex.value = -1;

                                redrawCanvas();
                                saveToHistory();
                            };
                            img.src = e.target.result;
                        };
                        reader.readAsDataURL(file);
                    }
                };
                fileInput.click();
            };

            // 图片状态检查函数
            const checkImagesUploaded = () => {
                if (currentMode.value === 'single') {
                    return originalImage !== null;
                } else {
                    const baseImage = document.getElementById('baseImage');
                    const blendImage = document.getElementById('blendImage');
                    return baseImage && baseImage.src && baseImage.style.display !== 'none' &&
                           blendImage && blendImage.src && blendImage.style.display !== 'none';
                }
            };

            // 保存修改
            const saveChanges = async () => {
                // 防止重复点击
                if (isProcessing.value) return;
                
                // 获取修改图片按钮
                const modifyButton = document.querySelector('.canvas-controls .el-button:nth-child(2)');
                if (!modifyButton) return;
                
                const originalText = modifyButton.textContent;
                
                try {
                    // 设置加载状态
                    isProcessing.value = true;
                    modifyButton.textContent = '处理中...';
                    modifyButton.disabled = true;
                    modifyButton.classList.add('loading');
                    
                    // 显示全局加载遮罩层
                    const loadingOverlay = document.getElementById('loadingOverlay');
                    if (loadingOverlay) {
                        loadingOverlay.classList.add('active');
                    }
                    
                    if (currentMode.value === 'single') {
                        const tempCanvas = document.createElement('canvas');
                        const tempCtx = tempCanvas.getContext('2d');
                        tempCanvas.width = canvas.width;
                        tempCanvas.height = canvas.height;

                        // 绘制背景图片
                        const bgCanvas = document.getElementById('backgroundCanvas');
                        if (bgCanvas && bgCanvas.style.display !== 'none') {
                            tempCtx.drawImage(bgCanvas, 0, 0);
                        }

                        // 绘制绘图内容
                        tempCtx.globalCompositeOperation = 'source-over';
                        tempCtx.drawImage(canvas, 0, 0);

                        // 将canvas转换为Blob - 使用Promise包装
                        const blob = await new Promise((resolve, reject) => {
                            tempCanvas.toBlob((blob) => {
                                if (blob) {
                                    resolve(blob);
                                } else {
                                    reject(new Error('无法转换图片'));
                                }
                            }, 'image/png');
                        });
                        
                        const formData = new FormData();
                        formData.append('image', blob, 'image.png');
                        formData.append('prompt', positivePrompt.value || '');
                        formData.append('cfgScale', positiveWeight.value || '7.5');
                        if (useAspectRatio.value) {
                            formData.append('aspectWidth', aspectWidth.value);
                            formData.append('aspectHeight', aspectHeight.value);
                        }

                        const response = await fetch('/system/ImageEdit/process-single', {
                            method: 'POST',
                            body: formData
                        });

                        if (response.ok) {
                            const result = await response.json();
                            if (!result.success) {
                                if (result.message === 'Token不足，请充值') {
                                    ElementPlus.ElMessage.error('您的token不足，无法进行修改图片');
                                } else {
                                ElementPlus.ElMessage.error(result.message);
                            }
                            // 恢复按钮状态
                            modifyButton.textContent = originalText;
                            modifyButton.disabled = false;
                            modifyButton.classList.remove('loading');
                            isProcessing.value = false;
                            
                            // 隐藏全局加载遮罩层
                            const loadingOverlay = document.getElementById('loadingOverlay');
                            if (loadingOverlay) {
                                loadingOverlay.classList.remove('active');
                            }
                            } else {
                                // 成功处理
                                const img = new Image();
                                img.onload = () => {
                                    originalImage = img;
                                    
                                    const container = document.querySelector('.canvas-container');
                                    const newWidth = container.clientWidth;
                                    const newHeight = container.clientHeight;
                                    
                                    canvas.width = newWidth;
                                    canvas.height = newHeight;
                                    
                                    const bgCanvas = document.getElementById('backgroundCanvas');
                                    if (bgCanvas) {
                                        bgCanvas.width = newWidth;
                                        bgCanvas.height = newHeight;
                                        bgCanvas.style.display = 'block';
                                        
                                        const bgCtx = bgCanvas.getContext('2d');
                                        bgCtx.clearRect(0, 0, bgCanvas.width, bgCanvas.height);
                                        
                                        const maxWidth = newWidth * 0.9;
                                        const maxHeight = newHeight * 0.9;
                                        const scale = Math.min(maxWidth / img.width, maxHeight / img.height);
                                        
                                        const scaledWidth = img.width * scale;
                                        const scaledHeight = img.height * scale;
                                        const offsetX = (newWidth - scaledWidth) / 2;
                                        const offsetY = (newHeight - scaledHeight) / 2;
                                        
                                        bgCtx.drawImage(img, offsetX, offsetY, scaledWidth, scaledHeight);
                                    }
                                    
                                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                                    rectangles.value = [];
                                    lassos.value = [];
                                    selectedRectIndex.value = -1;
                                    selectedLassoIndex.value = -1;
                                    historyStack.value = [];
                                    saveToHistory();
                                    
                                    // 图片加载完成后才恢复按钮状态
                                    modifyButton.textContent = originalText;
                                    modifyButton.disabled = false;
                                    modifyButton.classList.remove('loading');
                                    isProcessing.value = false;
                                    
                                    // 隐藏全局加载遮罩层
                                    const loadingOverlay = document.getElementById('loadingOverlay');
                                    if (loadingOverlay) {
                                        loadingOverlay.classList.remove('active');
                                    }
                                    
                                    ElementPlus.ElMessage.success('图片处理完成');
                                };
                                img.onerror = () => {
                                    ElementPlus.ElMessage.error('图片加载失败，请重试');
                                    // 图片加载失败时也恢复按钮状态
                                    modifyButton.textContent = originalText;
                                    modifyButton.disabled = false;
                                    modifyButton.classList.remove('loading');
                                    isProcessing.value = false;
                                    
                                    // 隐藏全局加载遮罩层
                                    const loadingOverlay = document.getElementById('loadingOverlay');
                                    if (loadingOverlay) {
                                        loadingOverlay.classList.remove('active');
                                    }
                                };
                                img.src = result.processedImageUrl;
                            }
                        } else {
                            throw new Error(`请求失败，状态码: ${response.status}`);
                        }
                    } else {
                        // 融合模式 - 保持不变
                        if (!checkImagesUploaded()) {
                            return;
                        }

                        const formData = new FormData();
                        const baseImg = document.getElementById('baseImage');
                        const blendImg = document.getElementById('blendImage');

                        const baseBlob = await imageToBlob(baseImg);
                        const blendBlob = await imageToBlob(blendImg);

                        formData.append('baseImage', baseBlob, 'base.png');
                        formData.append('blendImage', blendBlob, 'blend.png');
                        formData.append('prompt', positivePrompt.value);
                        formData.append('cfgScale', positiveWeight.value);
                        if (useAspectRatio.value) {
                            formData.append('aspectWidth', aspectWidth.value);
                            formData.append('aspectHeight', aspectHeight.value);
                        }

                        const response = await fetch('/system/ImageEdit/process-blend', {
                            method: 'POST',
                            body: formData
                        });

                        if (response.ok) {
                            const result = await response.json();
                            if (!result.success) {
                                if (result.message === 'Token不足，请充值') {
                                    ElementPlus.ElMessage.error('您的token不足，无法进行修改图片');
                                } else {
                                    ElementPlus.ElMessage.error(result.message);
                                }
                                // 恢复按钮状态
                                modifyButton.textContent = originalText;
                                modifyButton.disabled = false;
                                modifyButton.classList.remove('loading');
                                isProcessing.value = false;
                                
                                // 隐藏全局加载遮罩层
                                const loadingOverlay = document.getElementById('loadingOverlay');
                                if (loadingOverlay) {
                                    loadingOverlay.classList.remove('active');
                                }
                            } else {
                                const img = new Image();
                                img.onload = () => {
                                    originalImage = img;
                                    
                                    const container = document.querySelector('.canvas-container');
                                    const newWidth = container.clientWidth;
                                    const newHeight = container.clientHeight;
                                    
                                    canvas.width = newWidth;
                                    canvas.height = newHeight;
                                    
                                    const bgCanvas = document.getElementById('backgroundCanvas');
                                    if (bgCanvas) {
                                        bgCanvas.width = newWidth;
                                        bgCanvas.height = newHeight;
                                        bgCanvas.style.display = 'block';
                                        
                                        const bgCtx = bgCanvas.getContext('2d');
                                        bgCtx.clearRect(0, 0, bgCanvas.width, bgCanvas.height);
                                        
                                        const maxWidth = newWidth * 0.9;
                                        const maxHeight = newHeight * 0.9;
                                        const scale = Math.min(maxWidth / img.width, maxHeight / img.height);
                                        
                                        const scaledWidth = img.width * scale;
                                        const scaledHeight = img.height * scale;
                                        const offsetX = (newWidth - scaledWidth) / 2;
                                        const offsetY = (newHeight - scaledHeight) / 2;
                                        
                                        bgCtx.drawImage(img, offsetX, offsetY, scaledWidth, scaledHeight);
                                    }
                                    
                                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                                    rectangles.value = [];
                                    lassos.value = [];
                                    selectedRectIndex.value = -1;
                                    selectedLassoIndex.value = -1;
                                    historyStack.value = [];
                                    saveToHistory();
                                    
                                    // 图片加载完成后才恢复按钮状态
                                    modifyButton.textContent = originalText;
                                    modifyButton.disabled = false;
                                    modifyButton.classList.remove('loading');
                                    isProcessing.value = false;
                                    
                                    // 隐藏全局加载遮罩层
                                    const loadingOverlay = document.getElementById('loadingOverlay');
                                    if (loadingOverlay) {
                                        loadingOverlay.classList.remove('active');
                                    }
                                    
                                    ElementPlus.ElMessage.success('图片融合完成，剩余Token: ' + result.remainingTokens);
                                };
                                img.onerror = () => {
                                    ElementPlus.ElMessage.error('融合图片加载失败，请重试');
                                    // 图片加载失败时也恢复按钮状态
                                    modifyButton.textContent = originalText;
                                    modifyButton.disabled = false;
                                    modifyButton.classList.remove('loading');
                                    isProcessing.value = false;
                                    
                                    // 隐藏全局加载遮罩层
                                    const loadingOverlay = document.getElementById('loadingOverlay');
                                    if (loadingOverlay) {
                                        loadingOverlay.classList.remove('active');
                                    }
                                };
                                img.src = result.processedImageUrl;
                            }
                        } else {
                            throw new Error(`请求失败，状态码: ${response.status}`);
                        }
                    }
                } catch (error) {
                    console.error('Error:', error);
                    ElementPlus.ElMessage.error('处理失败: ' + error.message);
                    // 异常情况恢复按钮状态
                    isProcessing.value = false;
                    if (modifyButton) {
                        modifyButton.textContent = originalText;
                        modifyButton.disabled = false;
                        modifyButton.classList.remove('loading');
                    }
                    
                    // 隐藏全局加载遮罩层
                    const loadingOverlay = document.getElementById('loadingOverlay');
                    if (loadingOverlay) {
                        loadingOverlay.classList.remove('active');
                    }
                }
            };

            // 重新生成
            const regenerate = async () => {
                if (currentMode.value === 'single') {
                    const formData = new FormData();

                    const singleImg = document.getElementById('singleImage');
                    if (!singleImg || !singleImg.src || singleImg.style.display === 'none') {
                        alert('请先上传图片');
                        return;
                    }

                    const blob = await imageToBlob(singleImg);
                    formData.append('image', blob, 'single.png');
                    formData.append('prompt', positivePrompt.value);
                    formData.append('cfgScale', positiveWeight.value);

                    try {
                        const response = await fetch('/system/ImageEdit/process-single', {
                            method: 'POST',
                            body: formData
                        });
                        const result = await response.json();

                        if (!result.success) {
                            if (result.message === 'Token不足，请充值') {
                                window.location.href = '/system/ImageEdit/tokenError';
                            } else {
                                alert(result.message);
                            }
                        } else {
                            alert('重新生成完成，剩余Token: ' + result.remainingTokens);
                        }
                    } catch (error) {
                        console.error('Error:', error);
                        alert('处理失败: ' + error.message);
                    }
                } else {
                    if (!checkImagesUploaded()) return;

                    const formData = new FormData();

                    const baseImg = document.getElementById('baseImage');
                    const blendImg = document.getElementById('blendImage');

                    const baseBlob = await imageToBlob(baseImg);
                    const blendBlob = await imageToBlob(blendImg);

                    formData.append('baseImage', baseBlob, 'base.png');
                    formData.append('blendImage', blendBlob, 'blend.png');
                    formData.append('prompt', positivePrompt.value);
                    formData.append('cfgScale', positiveWeight.value);

                    try {
                        const response = await fetch('/system/ImageEdit/process-blend', {
                            method: 'POST',
                            body: formData
                        });
                        const result = await response.json();

                        if (!result.success) {
                            if (result.message === 'Token不足，请充值') {
                                window.location.href = '/system/ImageEdit/tokenError';
                            } else {
                                alert(result.message);
                            }
                        } else {
                            alert('重新生成完成，剩余Token: ' + result.remainingTokens);
                        }
                    } catch (error) {
                        console.error('Error:', error);
                        alert('处理失败: ' + error.message);
                    }
                }
            };

            // 下载图片
            const downloadImage = () => {
                if (!originalImage) {
                    ElementPlus.ElMessage.warning('请先上传图片');
                    return;
                }

                const tempCanvas = document.createElement('canvas');
                tempCanvas.width = originalImage.naturalWidth;
                tempCanvas.height = originalImage.naturalHeight;
                const tempCtx = tempCanvas.getContext('2d');

                tempCtx.drawImage(originalImage, 0, 0);

                const scaleX = tempCanvas.width / canvas.width;
                const scaleY = tempCanvas.height / canvas.height;
                tempCtx.save();
                tempCtx.scale(scaleX, scaleY);
                tempCtx.drawImage(canvas, 0, 0);
                tempCtx.restore();

                const link = document.createElement('a');
                link.download = 'edited-image.png';
                link.href = tempCanvas.toDataURL();
                link.click();

                ElementPlus.ElMessage.success('图片已下载');
            };

            // 复制到剪贴板
            const copyToClipboard = (type) => {
                const text = type === 'positive' ? positivePrompt.value : negativePrompt.value;
                if (!text) return;

                if (navigator.clipboard && navigator.clipboard.writeText) {
                    navigator.clipboard.writeText(text)
                        .then(() => {
                            ElementPlus.ElMessage.success('已复制到剪贴板');
                        })
                        .catch(() => {
                            fallbackCopyToClipboard(text);
                        });
                } else {
                    fallbackCopyToClipboard(text);
                }
            };

            // 备用复制方法（兼容旧浏览器）
            const fallbackCopyToClipboard = (text) => {
                const textArea = document.createElement('textarea');
                textArea.value = text;
                textArea.style.position = 'fixed';
                textArea.style.left = '-9999px';
                document.body.appendChild(textArea);
                textArea.focus();
                textArea.select();

                try {
                    document.execCommand('copy');
                    ElementPlus.ElMessage.success('已复制到剪贴板');
                } catch (err) {
                    ElementPlus.ElMessage.error('复制失败，请手动复制');
                }

                document.body.removeChild(textArea);
            };

            // 翻译文本
            const translateText = (type) => {
                let text = '';
                if (type === 'positive') {
                    text = positivePrompt.value;
                } else {
                    text = negativePrompt.value;
                }
                
                if (!text || text.trim() === '') {
                    ElementPlus.ElMessage.warning('请输入需要翻译的文字');
                    return;
                }
                
                ElementPlus.ElMessage.info('正在翻译...');
                
                // 调用后端腾讯翻译接口
                fetch(`/system/ImageEdit/text-translate-en?text=${encodeURIComponent(text)}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.success === 200) {
                                positivePrompt.value = data.translated_text;
                            ElementPlus.ElMessage.success('翻译成功');
                        } else {
                            ElementPlus.ElMessage.error(data.message || '翻译失败');
                        }
                    })
                    .catch(error => {
                        console.error('翻译请求失败:', error);
                        ElementPlus.ElMessage.error('翻译请求失败，请稍后重试');
                    });
            };

            // 清除文本
            const clearText = (type) => {
                if (type === 'positive') {
                    positivePrompt.value = '';
                } else {
                    negativePrompt.value = '';
                }
            };

            // 显示提示词对话框
            const showPromptDialog = (type) => {
                promptDialogVisible.value = true;
                currentPromptType.value = type;
            };

            // 确认提示词
            const confirmPrompt = () => {
                if (selectedPrompt.value) {
                    if (currentPromptType.value === 'positive') {
                        // 如果已有内容，先添加空格再追加新提示词
                        if (positivePrompt.value.trim()) {
                            positivePrompt.value += ' ' + selectedPrompt.value;
                        } else {
                            positivePrompt.value = selectedPrompt.value;
                        }
                    } else {
                        // 负向提示词同理
                        if (negativePrompt.value.trim()) {
                            negativePrompt.value += ' ' + selectedPrompt.value;
                        } else {
                            negativePrompt.value = selectedPrompt.value;
                        }
                    }
                }
                promptDialogVisible.value = false;
                selectedPrompt.value = '';
            };

            // 绘画相关方法
            const startDrawing = (e) => {
                // 检查是否已上传图片
                if (!originalImage) {
                    ElementPlus.ElMessage.warning('请先上传图片后再进行绘画操作');
                    return;
                }
                const coords = getCanvasCoordinates(e);

                if (currentTool.value === 'rectangle') {
                    // 检查是否点击了现有矩形
                    for (let i = rectangles.value.length - 1; i >= 0; i--) {
                        const rect = rectangles.value[i];
                        const controlPointIndex = isOnControlPoint(coords.x, coords.y, rect);

                        if (controlPointIndex !== -1) {
                            // 调整矩形大小
                            isResizing = true;
                            selectedRectIndex.value = i;
                            activeControlPoint = controlPointIndex;
                            return;
                        } else if (isPointInRect(coords.x, coords.y, rect)) {
                            // 拖拽矩形
                            isDraggingRect = true;
                            selectedRectIndex.value = i;
                            rectDragStartX = rect.startX;
                            rectDragStartY = rect.startY;
                            dragOffsetX = coords.x - rect.startX;
                            dragOffsetY = coords.y - rect.startY;
                            return;
                        }
                    }

                    // 创建新矩形
                    isDrawing.value = true;
                    startX = coords.x;
                    startY = coords.y;
                    endX = coords.x;
                    endY = coords.y;
                    selectedRectIndex.value = -1;
                } else if (currentTool.value === 'lasso') {
                    // 检查是否点击了现有套索
                    for (let i = lassos.value.length - 1; i >= 0; i--) {
                        const lasso = lassos.value[i];
                        if (isPointInLasso(coords.x, coords.y, lasso)) {
                            selectedLassoIndex.value = i;
                            return;
                        }
                    }

                    // 开始绘制新套索
                    selectedLassoIndex.value = -1;
                    isDrawingLasso = true;
                    currentLassoPath = [{x: coords.x, y: coords.y}];
                } else {
                    // 画笔或橡皮擦
                    isDrawing.value = true;
                    lastX.value = coords.x;
                    lastY.value = coords.y;
                    ctx.beginPath();
                    ctx.moveTo(lastX.value, lastY.value);
                }
            };

            const draw = (e) => {
                const coords = getCanvasCoordinates(e);

                if (currentTool.value === 'rectangle') {
                    if (isDraggingRect && selectedRectIndex.value !== -1) {
                        // 拖拽矩形
                        const rect = rectangles.value[selectedRectIndex.value];
                        const deltaX = coords.x - dragOffsetX - rect.startX;
                        const deltaY = coords.y - dragOffsetY - rect.startY;
                        rect.startX += deltaX;
                        rect.endX += deltaX;
                        rect.startY += deltaY;
                        rect.endY += deltaY;
                        redrawCanvas();
                    } else if (isResizing && selectedRectIndex.value !== -1) {
                        // 调整矩形大小
                        const rect = rectangles.value[selectedRectIndex.value];
                        switch (activeControlPoint) {
                            case 0: // 左上
                                rect.startX = coords.x;
                                rect.startY = coords.y;
                                break;
                            case 1: // 右上
                                rect.endX = coords.x;
                                rect.startY = coords.y;
                                break;
                            case 2: // 右下
                                rect.endX = coords.x;
                                rect.endY = coords.y;
                                break;
                            case 3: // 左下
                                rect.startX = coords.x;
                                rect.endY = coords.y;
                                break;
                        }
                        redrawCanvas();
                    } else if (isDrawing.value) {
                        // 绘制新矩形
                        endX = coords.x;
                        endY = coords.y;
                        redrawCanvas();
                        const validColor = brushColor.value && brushColor.value.match(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/) ? brushColor.value : '#000000';
                        const tempRect = {
                            startX: Math.min(startX, endX),
                            startY: Math.min(startY, endY),
                            endX: Math.max(startX, endX),
                            endY: Math.max(startY, endY),
                            color: validColor
                        };
                        drawSingleRectangle(tempRect, false);
                    }
                } else if (currentTool.value === 'lasso' && isDrawingLasso) {
                    // 添加新的点到当前套索路径
                    currentLassoPath.push({x: coords.x, y: coords.y});
                    redrawCanvas();

                    // 绘制正在绘制的套索
                    if (currentLassoPath.length > 1) {
                        const validColor = brushColor.value && brushColor.value.match(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/) ? brushColor.value : '#000000';
                        ctx.strokeStyle = validColor;
                        ctx.fillStyle = validColor + '66';
                        ctx.lineWidth = 2;

                        ctx.beginPath();
                        ctx.moveTo(currentLassoPath[0].x, currentLassoPath[0].y);
                        
                        for (let i = 1; i < currentLassoPath.length; i++) {
                            ctx.lineTo(currentLassoPath[i].x, currentLassoPath[i].y);
                        }
                        ctx.lineTo(coords.x, coords.y);
                        ctx.stroke();
                    }
                } else {
                    if (!isDrawing.value) return;

                    ctx.lineWidth = brushSize.value;
                    ctx.lineCap = 'round';
                    ctx.lineJoin = 'round';

                    if (currentTool.value === 'eraser') {
                        ctx.globalCompositeOperation = 'destination-out';
                    } else {
                        ctx.globalCompositeOperation = 'source-over';
                        ctx.strokeStyle = brushColor.value;
                    }

                    ctx.beginPath();
                    ctx.moveTo(lastX.value, lastY.value);
                    ctx.lineTo(coords.x, coords.y);
                    ctx.stroke();

                    lastX.value = coords.x;
                    lastY.value = coords.y;
                }
            };

            const stopDrawing = () => {
                if (currentTool.value === 'rectangle') {
                    if (isDrawing.value) {
                        const validColor = brushColor.value && brushColor.value.match(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/) ? brushColor.value : '#000000';
                        const newRect = {
                            startX: Math.min(startX, endX),
                            startY: Math.min(startY, endY),
                            endX: Math.max(startX, endX),
                            endY: Math.max(startY, endY),
                            color: validColor
                        };
                        if (Math.abs(newRect.endX - newRect.startX) < 5 || Math.abs(newRect.endY - newRect.startY) < 5) {
                            // 矩形太小，不添加
                        } else {
                            rectangles.value.push(newRect);
                            selectedRectIndex.value = rectangles.value.length - 1;
                        }
                        isDrawing.value = false;
                        saveToHistory();
                    }
                    isDraggingRect = false;
                    isResizing = false;
                    activeControlPoint = -1;
                } else if (currentTool.value === 'lasso') {
                    if (isDrawingLasso) {
                        isDrawingLasso = false;
                        if (currentLassoPath.length > 2) {
                            const validColor = brushColor.value && brushColor.value.match(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/) ? brushColor.value : '#000000';
                            lassos.value.push({
                                points: [...currentLassoPath],
                                color: validColor
                            });
                            selectedLassoIndex.value = lassos.value.length - 1;
                        }
                        currentLassoPath = [];
                        redrawCanvas();
                        saveToHistory();
                    }
                } else {
                    if (isDrawing.value) {
                        isDrawing.value = false;
                        saveToHistory();
                    }
                }
            };

            // 处理触摸事件
            const handleTouch = (e) => {
                e.preventDefault();
                const touch = e.touches[0];
                const mouseEvent = new MouseEvent(
                    e.type === 'touchstart' ? 'mousedown' :
                        e.type === 'touchmove' ? 'mousemove' : 'mouseup',
                    {
                        clientX: touch.clientX,
                        clientY: touch.clientY
                    }
                );
                canvas.dispatchEvent(mouseEvent);
            };

            // 辅助函数：将img元素转为Blob
            const imageToBlob = async (img) => {
                const response = await fetch(img.src);
                return response.blob();
            };

            // 生命周期钩子
            onMounted(() => {
                initCanvas();

                canvas.addEventListener('mousedown', startDrawing);
                canvas.addEventListener('mousemove', draw);
                canvas.addEventListener('mouseup', stopDrawing);
                canvas.addEventListener('mouseout', stopDrawing);
                canvas.addEventListener('dblclick', handleDoubleClick);

                canvas.addEventListener('touchstart', handleTouch);
                canvas.addEventListener('touchmove', handleTouch);
                canvas.addEventListener('touchend', stopDrawing);

                document.addEventListener('click', handleGlobalClick);

                // 防抖处理resize事件
                let resizeTimeout;
                const debouncedResize = () => {
                    clearTimeout(resizeTimeout);
                    resizeTimeout = setTimeout(() => {
                        initCanvas();
                    }, 100);
                };
                window.addEventListener('resize', debouncedResize);

                // 监听键盘事件，实现Ctrl+Z撤销
                document.addEventListener('keydown', (e) => {
                    if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) {
                        e.preventDefault();
                        undo();
                    }
                });
            });

            // 监听模式切换，清除上传的图片
            const { watch } = Vue;
            watch(currentMode, (newMode, oldMode) => {
                // 清除所有上传的图片显示
                const singleImage = document.getElementById('singleImage');
                const baseImage = document.getElementById('baseImage');
                const blendImage = document.getElementById('blendImage');
                
                if (singleImage) {
                    singleImage.src = '';
                    singleImage.style.display = 'none';
                }
                if (baseImage) {
                    baseImage.src = '';
                    baseImage.style.display = 'none';
                }
                if (blendImage) {
                    blendImage.src = '';
                    blendImage.style.display = 'none';
                }
                
                // 清除画布
                originalImage = null;
                redrawCanvas();
            });

            // 长宽比验证逻辑
            watch(aspectWidth, (newValue) => {
                if (newValue > 9 && aspectHeight.value > 9) {
                    aspectHeight.value = 9;
                }
            });

            watch(aspectHeight, (newValue) => {
                if (newValue > 9 && aspectWidth.value > 9) {
                    aspectWidth.value = 9;
                }
            });

            const confirmColor = () => {
                ElementPlus.ElMessage.success('颜色已选择: ' + brushColor.value);
            };

            return {
                currentTool,
                brushSize,
                brushColor,
                historyStack,
                currentMode,
                positivePrompt,
                negativePrompt,
                positiveWeight,
                negativeWeight,
                promptDialogVisible,
                selectedPrompt,
                setTool,
                clearCanvas,
                undo,
                setMode,
                uploadImage,
                uploadSingleImage,
                saveChanges,
                regenerate,
                downloadImage,
                copyToClipboard,
                translateText,
                clearText,
                showPromptDialog,
                confirmPrompt,
                confirmColor,
                rectangles,
                selectedRectIndex,
                aspectWidth,
                aspectHeight,
                useAspectRatio
            };
        }
    }).use(ElementPlus).mount('#app');
</script>
    
    <script>
        // 确保Element Plus样式加载完成后显示页面
        window.addEventListener('load', function() {
            document.body.style.visibility = 'visible';
            const buttons = document.querySelectorAll('.el-button');
            const cards = document.querySelectorAll('.el-card');
            buttons.forEach(btn => btn.style.visibility = 'visible');
            cards.forEach(card => card.style.visibility = 'visible');
        });
        
        // 如果Element Plus加载失败，也显示页面
        setTimeout(function() {
            document.body.style.visibility = 'visible';
            const buttons = document.querySelectorAll('.el-button');
            const cards = document.querySelectorAll('.el-card');
            buttons.forEach(btn => btn.style.visibility = 'visible');
            cards.forEach(card => card.style.visibility = 'visible');
        }, 2000);
    </script>
</body>
</html>
